package xgenerator.ui.swing.adapter;

import java.awt.Component;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;

import xgenerator.ui.swing.MetadataFileDialog;

public class MetadataFileAdapter extends AbstractAction {
	
	/**
	 * Serializable
	 */
	private static final long serialVersionUID = 1L;

	public static final String NEW_DIALOG_COMMAND = "NEW_DIALOG_COMMAND";
	public static final String LOAD_METADATA_COMMAND = "LOAD_METADATA_COMMAND";
	public static final String CANCEL_DIALOG_COMMAND = "CANCEL_DIALOG_COMMAND";

	/**
	 * UI组件
	 */
	private Component ui;

	/**
	 * constructor
	 * @param ui
	 */
	public MetadataFileAdapter(Component ui) {
		this.ui = ui;
	}

	/**
	 * <p>
	 * Title：actionPerformed
	 * </p>
	 * @author <a href="mailto:shushanlee@msn.com">liss</a>
	 * @param e
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	public void actionPerformed(ActionEvent e) {
		try {
			if (NEW_DIALOG_COMMAND.equals(e.getActionCommand())) {
				showMainActionPerformed(e);
			} else if (LOAD_METADATA_COMMAND.equalsIgnoreCase(e.getActionCommand())) {
				loadFileActionPerformed(e);
			} else if (CANCEL_DIALOG_COMMAND.equalsIgnoreCase(e.getActionCommand())) {
				closeMainActionPerformed(e);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			JOptionPane.showMessageDialog(ui, ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
		}
	}
	
	/**
	 * <p>
	 * Title：显示主界面
	 * </p>
	 * @author <a href="mailto:shushanlee@msn.com">liss</a>
	 * @param e
	 */
	private void showMainActionPerformed(ActionEvent e) {
		new MetadataFileDialog((Frame) ui, "", true);
	}
	
	/**
	 * <p>
	 * Title：关闭主界面
	 * </p>
	 * @author <a href="mailto:shushanlee@msn.com">liss</a>
	 * @param e
	 */
	private void closeMainActionPerformed(ActionEvent e) {
		((MetadataFileDialog) ui).dispose();
	}
	
	/**
	 * <p>
	 * Title：加载元数据文件
	 * </p>
	 * @author <a href="mailto:shushanlee@msn.com">liss</a>
	 * @param e
	 */
	private void loadFileActionPerformed(ActionEvent e) {
		MetadataFileDialog metadataFileDialog = (MetadataFileDialog) ui;
		String filePath = metadataFileDialog.getFilePathField().getText();
		if(null == filePath || "".equals(filePath)) {
			throw new RuntimeException("请选择文件！");
		}
		File file = new File(filePath);
		if(!file.exists()) {
			throw new RuntimeException("文件" + filePath + "不存在！");
		}
		
		System.out.println(filePath);
	}

	/**
	 * <p>
	 * Title：
	 * </p>
	 * @author <a href="mailto:shushanlee@msn.com">liss</a>
	 * @return
	 */
	public Component getUI() {
		return ui;
	}

	/**
	 * <p>
	 * Title：
	 * </p>
	 * @author <a href="mailto:shushanlee@msn.com">liss</a>
	 * @param ui
	 */
	public void setUI(Component ui) {
		this.ui = ui;
	}

}
